package ru.ifmo.itmokis.sim;

import org.apache.log4j.Logger;
import ru.ifmo.itmokis.algo.SupplyBuilder;
import ru.ifmo.itmokis.domain.Time;
import ru.ifmo.itmokis.util.Config;
import ru.ifmo.itmokis.util.EventDriven;
import ru.ifmo.itmokis.util.Randoms;

/**
 *
 * @author Ivan Stepuk
 */
public class SupplyFactory implements ClockListener, EventDriven {

    public static final Time PERIOD = new Time(1, 0, 0);
    private SupplyBuilder supplyBuilder;
    private DeliveryFactory deliveryFactory;
    private Config config;
    private Randoms randoms;
    // ^ Dependencies ^
    private Time nextEventTime = Time.ZERO;
    

    public SupplyFactory(SupplyBuilder supplyBuilder, DeliveryFactory deliveryFactory, Config config, Randoms randoms) {
        this.supplyBuilder = supplyBuilder;
        this.deliveryFactory = deliveryFactory;
        this.config = config;
        this.randoms = randoms;
    }

    @Override
    public void process(Time time) {
        if (time.equals(nextEventTime)) {
            supplyBuilder.commitPlan(time);
            Time deliveryTime = time.add(randoms.gammaTime(
                    config.getTime("SupplyTime"),
                    config.getInt("SupplyScale")));
            Logger.getLogger(getClass()).debug(time + ": New material supply order, del @ " + deliveryTime);
            deliveryFactory.scheduleEvent(deliveryTime);

            scheduleEvent(nextEventTime.add(PERIOD));
        }
    }

    @Override
    public void scheduleEvent(Time time) {
        nextEventTime = time;
    }
}
